// Vue
import Vue from 'vue';
import App from './App';
import util from '@/libs/util';

// 配置
import Setting from './setting';

// 混合
import mixinApp from '@/mixins/app';

// 插件
import plugins from '@/plugins';

// store
import store from '@/store/index';

// iView 和 iView Pro
import ViewUI from 'view-design';
import iViewPro from '@/libs/iview-pro/iview-pro.min.js';
import './assets/my-theme/color.less';

// 菜单和路由
import router from './router';
// import menuHeader from '@/menu/header';
// import menuSider from '@/menu/sider';
import { frameInRoutes } from '@/router/routes';

// 多语言
import i18n from '@/i18n';

// 方法
import { getHeaderName, getMenuSider, getSiderSubmenu } from '@/libs/system';

// 内置组件
import iLink from '@/components/link';
import iFrame from '@/components/frame';
import '@/directives/index.js'; // 自定义指令按钮

// 组件（author：黄旗）
import JGtable from '@/components/table';
import JGsearch from '@/components/search';
// 方法（author：黄旗）
import log from './libs/Debug.js';
// import CKEditor from '@ckeditor/ckeditor5-vue2'
// 使用样式，修改主题可以在 styles 目录下创建新的主题包并修改 iView 默认的 less 变量
// 参考 https://www.iviewui.com/docs/guide/theme
// import './styles/coustom.less';
// import './styles/original.less';
import './styles/index.less'
import './libs/iview-pro/iview-pro.css';
// import VueLazyLoad from 'vue-lazyload'
// Vue.use(VueLazyLoad, {
//     preLoad: 1,
//     error: require('./assets/images/error.jpg'),
//     loading: require('./assets/images/loading.jpg'),
//     attempt: 1,
//   })
//select搜索filterable重写只匹配name
ViewUI.Select.props.onlyFilterWithText = {
    type: Boolean,
    default: false
  };
  ViewUI.Select.methods.originValidateOption = ViewUI.Select.methods.validateOption;
  ViewUI.Select.methods.validateOption = function ({children, elm, propsData}) {
      if (this.onlyFilterWithText) {
        const textContent = (elm && elm.textContent) || (children || []).reduce((str, node) => {
            const nodeText = node.elm ? node.elm.textContent : node.text;
            return `${str} ${nodeText}`;
        }, '') || '';
        const query = this.query.toLowerCase().trim();
        return textContent.toLowerCase().includes(query);
      } else {
        return this.originValidateOption({children, elm, propsData});
      }
  };
  //因为iview内部的validateOption函数不仅会匹配conName，还会匹配conCode。只要其中有一项匹配，那么这条数据就会被选中。我们现在重写iview的validateOption函数，让它只匹配conName
  Vue.use(ViewUI, {
    i18n: (key, value) => i18n.t(key, value)
  })
Vue.component('JG-table', JGtable);
Vue.component('JG-search', JGsearch); // 开发打印
Vue.prototype.log = log;
// 皮肤的切换
if (util.storage.get('dark') === true) {
    document.getElementsByTagName('body')[0].classList.add('dark');
    document.getElementsByTagName('body')[0].classList.add('ivu-theme-dark');
} else {
    document.getElementsByTagName('body')[0].classList.add('witle');
 
}
if (window) window.$t = (key, value) => i18n.t(key, value);

Vue.use(plugins);

Vue.use(ViewUI, {
    i18n: (key, value) => i18n.t(key, value)
});
Vue.use(iViewPro);
Vue.component('i-link', iLink);
Vue.component('i-frame', iFrame);

new Vue({
    mixins: [mixinApp],
    router,
    store,
    i18n,
    render: h => h(App),
    created () {
        if (sessionStorage.getItem("store")) {
            console.log('页面重新加载');
            let storet = sessionStorage.getItem("store");
            this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(storet == null ? '' : storet)))
          }
          //在页面刷新时将vuex里的信息保存到sessionStorage里
          window.addEventListener("beforeunload", () => {
            console.log('页面被刷新');
            let state = JSON.stringify(this.$store.state)
            sessionStorage.setItem("store", state == null ? '' : state)
          })
        // 处理路由 得到每一级的路由设置
        this.$store.commit('admin/page/init', frameInRoutes);
        // 设置顶栏菜单
        let menus = util.storage.get('menus');
        // let menus = JSON.parse(localStorage.getItem('menus'));
        let project =util.storage.get('project');
        let currentProject = util.storage.get('currentProject');
        // console.log(project,'project',currentProject,'currentProject')
        if(!project||!currentProject){
            router.push({
                name: 'login',
            });
        }
        if (menus) {
            this.$store.commit('admin/menu/setHeader', menus.header);
        }else{
            router.push({
                name: 'login',
            });
        }
        // 加载用户登录的数据
        this.$store.dispatch('admin/account/load');
        // 初始化全屏监听
        this.$store.dispatch('admin/layout/listenFullscreen')
    },
    watch: {
        // 监听路由 控制侧边栏显示 标记当前顶栏菜单（如需要）
        $route (to, from) {
            if (
                util.storage.get('menus') &&
                util.storage.get('menus') !== '{}'
            ) {
                const path = to.path;
                let menus
                menus = util.storage.get('menus')
                const headerName = getHeaderName(path, menus.sider);
                // console.log(headerName, 'headerName')
                this.$store.commit('admin/menu/setHeaderName', headerName);
                let filterMenuSider;
                filterMenuSider = getMenuSider(menus.sider, headerName);
                this.$store.commit('admin/menu/setSider', filterMenuSider);
                this.$store.commit('admin/menu/setActivePath', path);
                const openNames = getSiderSubmenu(path, menus.sider);
                this.$store.commit('admin/menu/setOpenNames', openNames);
                this.appRouteChange(to, from);
            }
        }
        // 监听路由 控制侧边栏显示 标记当前顶栏菜单（如需要）||金典模式
        // '$route' (to, from) {
        //     let path = to.matched[to.matched.length - 1].path;
        //     let menuSiders = util.storage.get('menus') ? util.storage.get('menus').sider : []
        //     if (menuSiders.length > 0) {
        //         for (let item of menuSiders) {
        //             item.header = 'home'
        //             if (item.children) {
        //                 for (let items of item.children) {
        //                     items.header = 'home'
        //                 }
        //             }
        //         }
        //         let headerName = getHeaderName(path, menuSiders);
        //         if (headerName === null) {
        //             path = to.path;
        //             headerName = getHeaderName(path, menuSiders);
        //         }
        //         // 在 404 时，是没有 headerName 的
        //         if (headerName !== null) {
        //             this.$store.commit('admin/menu/setHeaderName', headerName);
        //             this.$store.commit('admin/menu/setMenuSider', menuSiders);

        //             const filterMenuSider = getMenuSider(menuSiders, headerName);
        //             this.$store.commit('admin/menu/setSider', filterMenuSider);
        //             this.$store.commit('admin/menu/setActivePath', to.path);

        //             const openNames = getSiderSubmenu(path, menuSiders);
        //             this.$store.commit('admin/menu/setOpenNames', openNames);
        //         }
        //     }
        //     this.appRouteChange(to, from);
        // }
    }
}).$mount('#app');
